package service

import (
	"database/sql"
	"errors"
	"fmt"
	"strings"
	"time"
	"your-tool/internal/entity"
	"your-tool/internal/global"
)

// 获取动漫列表
func AcgList(searchName string, week string, status int) (list []*entity.AcgEntity,err error) {
	global.InitDB()
	selectSql := `select id,name,search_name,week,level,status,create_time,update_time from acg where status=? `
	r, err := global.DB.Query(selectSql, status)
	if err != nil && err != sql.ErrNoRows {
		return nil, err
	}
	// fmt.Println(searchName, week, status)
	list = make([]*entity.AcgEntity, 0)
	for r.Next() {
		var tmp entity.AcgEntity
		_ = r.Scan(&tmp.Id, &tmp.Name, &tmp.SearchName, &tmp.Week, &tmp.Level, &tmp.Status, &tmp.CreateTime, &tmp.UpdateTime)
		// 关闭的就是全部
		if(status == 0) {
			list = append(list, &tmp)
		} else {
			if(searchName != "" && week != ""){
				if(strings.Contains(tmp.SearchName, searchName) && strings.Contains(tmp.Week, week)) {
					list = append(list, &tmp)
				}
			} else if(searchName != ""){
				if(strings.Contains(tmp.SearchName, searchName)) {
					list = append(list, &tmp)
				}
			} else if(week != "") {
				if(strings.Contains(tmp.Week, week)) {
					list = append(list, &tmp)
				}
			}
		}
	}
	return list, nil
}


// 添加动漫
func AcgCreate(acg *entity.AcgEntity) (err error) {

	if(acg.Name == ""){
		return errors.New("动漫名称不能为空")
	}
	if(acg.SearchName == ""){
		return errors.New("搜索名称不能为空")
	}
	if(acg.Week == ""){
		return errors.New("星期不能为空")
	}
	if(acg.Level < 1){
		return errors.New("追更集数不能为空")
	}
	acg.Status = 1
	dateTime := time.Now().Format("2006-01-02 15:04:05")
	acg.CreateTime = dateTime
	acg.UpdateTime = dateTime

	global.InitDB()

	var a entity.AcgEntity
	selectSql := "select id,name from acg where name=? limit 1"
	err = global.DB.QueryRow(selectSql, acg.Name).Scan(&a.Id, &a.Name)
	if err != nil && err != sql.ErrNoRows {
		return err
	}
	if a.Id > 0 {
		return errors.New("已存在同名动漫")
	}

	inserSql := "insert into acg(name,search_name,week,level,status,create_time,update_time) values (?,?,?,?,?,?,?)"
	_, err = global.DB.Exec(inserSql, acg.Name, acg.SearchName, acg.Week, acg.Level, acg.Status, acg.CreateTime, acg.UpdateTime)
	if err != nil {
		return err
	}
	return nil
}


// 修改动漫
func AcgUpdate(acg *entity.AcgEntity) (err error) {
	global.InitDB()
	updateSql := fmt.Sprintf("update acg set level=%d,status=%d where id=?", acg.Level, acg.Status) 
	_, err = global.DB.Exec(updateSql, acg.Id)
	if err != nil && err != sql.ErrNoRows {
		return err
	}
	return nil
}


// 获取动漫
func AcgItem(id int) (acg *entity.AcgEntity, err error) {
	global.InitDB()
	selectSql := "select id,name,search_name,week,level,status,create_time,update_time from acg where id=? limit 1"
	err = global.DB.QueryRow(selectSql, id).Scan(&acg.Id, &acg.Name, &acg.SearchName, &acg.Week, &acg.Level, &acg.Status, &acg.CreateTime, &acg.UpdateTime)
	if err != nil && err != sql.ErrNoRows {
		return nil, err
	}
	return acg, nil
}



// 完结动漫